import streamlit as st
import requests
from typing import List, Dict, Optional
from strings import CACHE_TTL, API_BASE_URL

# API调用函数
@st.cache_data(ttl=CACHE_TTL)  # 缓存5分钟
def get_frameworks() -> Optional[List[Dict]]:
    """获取部门信息"""
    try:
        response = requests.get(f"{API_BASE_URL}/frameworks", timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get('code') == 200:
                return data.get('data', [])
        return None
    except Exception as e:
        st.error(f"获取部门信息失败: {str(e)}")
        return None

@st.cache_data(ttl=CACHE_TTL)  # 缓存1小时
def get_projects() -> Optional[List[Dict]]:
    """获取项目信息"""
    try:
        response = requests.get(f"{API_BASE_URL}/projects", timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get('code') == 200:
                return data.get('data', [])
        return None
    except Exception as e:
        st.error(f"获取项目信息失败: {str(e)}")
        return None

def get_report_data(query_params: Dict) -> Optional[Dict]:
    """获取报告数据"""
    try:
        response = requests.post(
            f"{API_BASE_URL}/reports", 
            json=query_params,
            timeout=300,  # 5分钟超时，适应大数据量和AI生成时间
            headers={'Content-Type': 'application/json'}
        )
        
        if response.status_code == 200:
            data = response.json()
            if data.get('code') == 200:
                return data.get('data', {})
            else:
                st.error(f"API返回错误: {data.get('message', '未知错误')}")
                return None
        else:
            st.error(f"API请求失败: HTTP {response.status_code}")
            return None
            
    except requests.exceptions.Timeout:
        st.error("⏰ API请求超时，请稍后重试")
        return None
    except requests.exceptions.ConnectionError:
        st.error("🔌 无法连接到API服务，请检查服务是否正常运行")
        return None
    except Exception as e:
        st.error(f"获取报告数据失败: {str(e)}")
        return None